package dao.jpa;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import javax.persistence.Query;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import util.UtilString;
import dao.ParcelaTransacaoDAO;
import entity.CategoriaTransacao;
import entity.ParcelaTransacao;
import entity.Transacao;

@Repository
public class ParcelaTransacaoJpaDAO extends GenericJpaDAO<ParcelaTransacao>
		implements ParcelaTransacaoDAO, Serializable {

	private static final long serialVersionUID = 2678582808176831603L;

	@SuppressWarnings("unchecked")
	@Override
	public List<ParcelaTransacao> listarParcelasPorPeriodoECategoria(
			final Date dataInicial, final Date dataFinal,
			CategoriaTransacao categoriaTransacao, boolean quitada) {

		final Criteria criteria = criarCriteria();
		criteria.add(Restrictions.between("dataPagamento", dataInicial,
				dataFinal));
		criteria.createAlias("transacao", "t");
		criteria.add(Restrictions
				.eq("t.categoriaTransacao", categoriaTransacao));

		criteria.add(Restrictions.eq("quitada", quitada));

		return criteria.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<ParcelaTransacao> listarParcelasPorExemploEPeriodoVencimento(
			final ParcelaTransacao parcelaTransacao, final Date dataInicial,
			final Date dataFinal) {

		final Transacao transacao = parcelaTransacao.getTransacao();

		final Criteria criteria = criarCriteria();
		criteria.createAlias("transacao", "t");

		if (!UtilString.isStringVazia(transacao.getDescricao())) {
			criteria.add(Restrictions.like("t.descricao",
					transacao.getDescricao()));
		}

		if (transacao.getCategoriaTransacao() != null) {
			criteria.add(Restrictions.eq("t.categoriaTransacao",
					transacao.getCategoriaTransacao()));
		}

		if (transacao.getConta() != null) {
			criteria.add(Restrictions.eq("t.conta", transacao.getConta()));
		}

		criteria.add(Restrictions.between("dataVencimento", dataInicial,
				dataFinal));

		return criteria.list();
	}

	@Override
	public void removerParcelasTransacao(Transacao transacao) {

		final Query query = getEntityManager().createQuery(
				"delete from ParcelaTransacao where transacao = :transacao");
		query.setParameter("transacao", transacao);
		query.executeUpdate();
	}
}
